package cn.edu.tju.fctl.rest.aspect;

import cn.edu.tju.fctl.entities.User;
import cn.edu.tju.fctl.util.BizCode;
import cn.edu.tju.fctl.util.ShiroUtil;
import cn.edu.tju.fctl.util.StateCode;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * Created by catold on 15/12/18.
 */
@Aspect
public class LoginAspectInterceptor {

    @Pointcut("execution(* cn.edu.tju.fctl.rest.*.*(..)) && !withoutAuthorization()")
    public void loginCheck(){

    }

    @Pointcut("execution(* cn.edu.tju.fctl.rest.UserRest.user*(..)) ||" +
            "execution(* cn.edu.tju.fctl.rest.VacationTypeRest.*(..))" +
            "|| execution(* cn.edu.tju.fctl.rest.FileRest.*(..))" +
            "|| execution(* cn.edu.tju.fctl.rest.UserRest.noop())" +
            "|| execution(* cn.edu.tju.fctl.rest.VacationViewRest.*(..))")
    public void withoutAuthorization(){

    }

    @Around("loginCheck()")
    public Object validateUser(ProceedingJoinPoint jp) throws Exception {
        if (!ShiroUtil.isAuthenticated()) {
            return StateCode.buildCode(BizCode.WITHOUT_AUTHORIZATION);
        } else {
            try {
                return jp.proceed();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                return StateCode.buildCode(BizCode.FAIL);
            }
        }
    }
}
